package com.knowledgePointsByMyTest.JavaBIO;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author yulongtian
 * @create 2024-11-04 10:38
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务端绑定端口，开启监听");
        while (true) {
            Socket socket = serverSocket.accept();//socket代表了一个客户端连接,accept是阻塞的
            System.out.println("接收了一个客户端连接:socket=" + socket);
            new Thread(new ServerHandler(socket)).start();
        }

    }

    static class ServerHandler implements Runnable {

        private Socket socket;

        public ServerHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            //负责读写数据 业务操作
            try {
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

                while (true) {
                    String line = reader.readLine();
                    System.out.println("收到了来自客户端的数据:" + line);
                    //业务操作

                    //向客户端写数据
                    writer.write("hello bio client, i am bioserver\n");
                    writer.flush();
                }


            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
